from datetime import datetime
from .. import db
from ..database import save_db_data

class Sensor:
    def __init__(self, name, device_type, field_id, id=None, is_online=True, 
                location=None, sim_expire_date=None, sim_status=None):
        self.id = id if id is not None else len(db.sensors) + 1
        self.name = name
        self.device_type = device_type  # soil_moisture, irrigation, weather
        self.field_id = field_id
        self.is_online = is_online
        self.location = location or {}  # {lat: xx, lng: xx}
        self.sim_expire_date = sim_expire_date
        self.sim_status = sim_status  # active, expiring, expired
        self.created_at = datetime.utcnow()
    
    def save(self):
        """保存设备信息"""
        if not hasattr(self, 'id'):
            self.id = len(db.sensors) + 1
        if self not in db.sensors:
            db.sensors.append(self)
        save_db_data()  # 保存到文件
        return self
    
    @staticmethod
    def find_by_id(sensor_id):
        """通过ID查找设备"""
        for sensor in db.sensors:
            if sensor.id == int(sensor_id):
                return sensor
        return None
    
    @staticmethod
    def find_by_field(field_id):
        """查找农田的设备"""
        return [sensor for sensor in db.sensors if sensor.field_id == field_id]
    
    def update(self, data):
        """更新设备信息"""
        try:
            self.name = data.get('name', self.name)
            self.device_type = data.get('device_type', self.device_type)
            self.field_id = data.get('field_id', self.field_id)
            self.is_online = data.get('is_online', self.is_online)
            self.location = data.get('location', self.location)
            self.sim_expire_date = data.get('sim_expire_date')
            self.sim_status = data.get('sim_status')
            return True
        except Exception as e:
            print(f"Error updating sensor: {str(e)}")
            return False
    
    def delete(self):
        """删除设备"""
        try:
            db.sensors.remove(self)
            return True
        except Exception as e:
            print(f"Error deleting sensor: {str(e)}")
            return False
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'name': self.name,
            'device_type': self.device_type,
            'field_id': self.field_id,
            'is_online': self.is_online,
            'location': self.location,
            'sim_expire_date': self.sim_expire_date.isoformat() if self.sim_expire_date else None,
            'sim_status': self.sim_status,
            'created_at': self.created_at.isoformat()
        }

class SensorData:
    def __init__(self, sensor_id, data_type, value, timestamp=None, id=None):
        self.id = id if id is not None else len(db.sensor_data) + 1
        self.sensor_id = sensor_id
        self.data_type = data_type
        self.value = value
        self.timestamp = timestamp or datetime.utcnow()
    
    def save(self):
        """保存数据"""
        if not hasattr(self, 'id'):
            self.id = len(db.sensor_data) + 1
        db.sensor_data.append(self)
        return self
    
    @staticmethod
    def find_by_sensor(sensor_id, start_time=None, end_time=None, limit=100):
        """查找设备数据"""
        data = [d for d in db.sensor_data if d.sensor_id == sensor_id]
        
        if start_time:
            data = [d for d in data if d.timestamp >= start_time]
        if end_time:
            data = [d for d in data if d.timestamp <= end_time]
            
        return sorted(data, key=lambda x: x.timestamp, reverse=True)[:limit]
    
    def to_dict(self):
        """转换为字典"""
        return {
            'id': self.id,
            'sensor_id': self.sensor_id,
            'data_type': self.data_type,
            'value': self.value,
            'timestamp': self.timestamp.isoformat()
        } 